<?php defined('SYSPATH') or die('No direct script access.');

	class Controller_Test extends Controller{
		
		
		
		public function action_index(){
			/*
			 * 
			 * $jsonRequest = Zend_Json::decode($_POST['user'],Zend_Json::TYPE_OBJECT);
				Model::factory("services_user")->save($jsonRequest);
				$this->action_index();
			 * 
			 * 
			 
			 * 
			 * */	
		}
		
		public function action_sportcontent(){
			$sport = ORM::factory("dao_sport")->where("sport_name","=","Futbol")->count_all();
			Fire::log($sport);
			$this->request->response = $sport;
		}
		
		public function action_pdfreport(){
			$pdf = new Zend_Pdf();
			
			// Update the PDF document
			//$pdf->save($fileName, true);
			// Save document as a new file
			//$pdf->save($newFileName);
 
			// Return the PDF document as a string
			//$pdfString = $pdf->render();
			
			$pdfPage = new Zend_Pdf_Page(Zend_Pdf_Page::SIZE_A4);
			$pageWidth = $pdfPage->getWidth();
			$pageHeight = $pdfPage->getHeight();
			
			//$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
			// Apply font
			//$pdfPage->setFont($font, 18);
			
			//$pdfPage->drawText("Informe de Paciente",$pageWidth - $pageWidth/2, 0);

			//$chompImage = Zend_Pdf_Image::imageWithPath("C:\wamp\www\diastole\media\img\myphoto.jpg");
			$chompImage = Zend_Pdf_Image::imageWithPath("media\img\content\logo.png");

        	$imageHeight = 72;
        	$imageWidth = 72;

        	$topPos = $pageHeight - 36;
        	$leftPos = 36;
        	$bottomPos = $topPos - $imageHeight;
        	$rightPos = $leftPos + $imageWidth;

        	$pdfPage->drawImage($chompImage, $leftPos, $bottomPos, $rightPos, $topPos);	
			

			// Add new page
			//$pdf->pages[] = $pdf->newPage(Zend_Pdf_Page::SIZE_A4);
			
			// Add new page
			$pdf->pages[] = $pdfPage;
			
			header('Content-type: application/pdf'); //Enviaremos un PDF			
			header('Content-Disposition: attachment; filename="descarga.pdf"'); //Se va a llamar descarga.pdf
						
			$this->request->response = $pdf->render();
				
		}
		
		public function action_dompdfreport(){
						
			// Load a view using the PDF extension
		    //$pdf = View_PDF::factory('pdf/example');
		    
		    $pdf = View_PDF::factory('template-sections/content-multiflex');
		    
		    // Use the PDF as the request response
		    ini_set("memory_limit","20M");
		    $this->request->response = $pdf->render();
		    
		    // Display the PDF in the browser as "my_pdf.pdf"
		    // Remove "inline = TRUE" to force the PDF to be downloaded
		    //$this->request->send_file(TRUE, 'my_pdf.pdf', array('inline' => TRUE));
		    $this->request->send_file(TRUE, 'report.pdf');
			
		}
		
		
		public function action_rtfreport(){
			
			
		}
		
		public function action_xlsexport(){
			
			ini_set("memory_limit","20M");
			
			//ws stands for WorkSheet
			
			$ws = new Spreadsheet(array(
						'author'       => 'Kohana-PHPExcel',
						'title'	       => 'Report',
						'subject'      => 'Subject',
						'description'  => 'Description',
    		));
    
    		$ws->set_active_sheet(0);
    		$as = $ws->get_active_sheet();
    		$as->setTitle('Report');
    
    		$as->getDefaultStyle()->getFont()->setSize(9);
    
    		$as->getColumnDimension('A')->setWidth(7);
    		$as->getColumnDimension('B')->setWidth(40);
    		$as->getColumnDimension('C')->setWidth(12);
    		$as->getColumnDimension('D')->setWidth(10);
    
    		$sh = array(
				1 => array('Day','User','Count','Price'),
				2 => array(1, 'John', 5, 587),
				3 => array(2, 'Den', 3, 981),
				4 => array(3, 'Anny', 1, 214)
    		);
    
    		$ws->set_data($sh, false);
    		
    		$ws->set_active_sheet(0);
    		    		
    		//Para que funcionara tuve que crear un directorio para el almacenamiento temporal de los 
    		//archivos xls => diastole/assets/downloads/spreadsheets --> nooooooo, simplemente necesitaba mas memoria
    		//este directorio debiera de poder ser configurable
    		$ws->send(array('name'=>'report', 'format'=>'Excel5'));
			
			
		}
		
		public function action_seereport(){
			$this->request->response = View::factory("analysis/report-template")->render();
			
		}
		
		public function action_samplegrid(){
			$grid = new Jqgrid("test", Helper_Service::factory("test"));
			$this->request->response = $grid->render("jqgrid/config/test");		
		}
		
		public function action_list(){
			$grid = new Jqgrid("test", Helper_Service::factory("test"));
			$criteria = new Jqgrid_Criteria();
			$criteria->page = $_POST['page'];
			$criteria->limit = $_POST['rows'];
			$criteria->sidx = $_POST['sidx'];
			$criteria->sord = $_POST['sord'];
			$this->request->response = $grid->getList($criteria);
		}
		
		public function action_save(){
			$grid = new Jqgrid("test", Helper_Service::factory("test"));
			$this->request->response = $grid->save($_POST['oper'],$_POST);
		}
		
		
		public function action_newtabs(){
			
			$analysis = Helper_Service::factory("analysis",1); 
			
			$segment = $analysis->getFinalSegment();
			$result = $analysis->getResults();
								
			$view = View::factory("page");
			$param_view = View::factory("analysis/parameters");
			$param_view->params = array('aod_value'=>$result->aod_value,
										'iar_value'=>$result->iar_value,
										'aos_value'=>$result->aos_value,
			                            'imc_value'=>'25.95',
			                            'fc_value'=>'120');
			
			$param_view->signal = array('sampling_period'=>'4.9',
										'num_samples'=>$segment->length,
										'max_value'=>$segment->max,
										'min_value'=>$segment->min);
			
			$view->page_content = $param_view->render(); 
			
			$view->scripts = array(	'media/js/jqplot/jquery.jqplot.min.js',
									'media/js/jqplot/plugins/jqplot.canvasTextRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.canvasAxisLabelRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.highlighter.min.js',
									'media/js/jqplot/plugins/jqplot.cursor.min.js',
									'media/js/jqplot/plugins/jqplot.dateAxisRenderer.min.js',
									'media/js/js_controls/js_chart.js');
			$view->user_script = View::factory('js-user-scripts/final-segment')->set("chart_data",$segment->toJSON());

			$actions = array();
			$actions[] = array("url"=>"/diastole/test/chartparameters","text"=>"Chart Parameters");
			//Tabs creation
			$new_tabs = View::factory("components/tabs");
			$new_tabs->actions = $actions;
			//$new_tabs->section_content = $view->render();
			
			$this->request->response = $new_tabs->render();
			
		}
		
		
		public function action_chartparameters(){
			$analysis = Helper_Service::factory("analysis",1); 
			
			$segment = $analysis->getFinalSegment();
			$result = $analysis->getResults();
			
			
			//$aos_segment = Model::factory("segment");
			//$aos_segment->samples[round(floatval(),4)] = 
			//$aod_segment = Model::factory("segment");
			//$iar_segment = Model::factory("segment");
			//$iar_segment->samples[round(floatval($result->iar_x1),4)] = floatval($result->iar_y1);
			//$iar_segment->samples[round(floatval($result->iar_x2),4)] = floatval($result->iar_y2);
						
			//Fire::log($iar_segment->toJSON());
						
			$view = View::factory("page");
			$param_view = View::factory("analysis/parameters");
			$param_view->params = array('aod_value'=>$result->aod_value,
										'iar_value'=>$result->iar_value,
										'aos_value'=>$result->aos_value,
			                            'imc_value'=>'25.95',
			                            'fc_value'=>'120');
			
			$param_view->signal = array('sampling_period'=>'4.9',
										'num_samples'=>$segment->length,
										'max_value'=>$segment->max,
										'min_value'=>$segment->min);
			
			$view->page_content = $param_view->render(); 
			
			$view->scripts = array(	'media/js/jqplot/jquery.jqplot.min.js',
									'media/js/jqplot/plugins/jqplot.canvasTextRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.canvasAxisLabelRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.canvasAxisTickRenderer.min.js',
									'media/js/jqplot/plugins/jqplot.highlighter.min.js',
									'media/js/jqplot/plugins/jqplot.cursor.min.js',
									'media/js/jqplot/plugins/jqplot.dateAxisRenderer.min.js',
									'media/js/js_controls/js_chart.js');
			
						
			$view->user_script = View::factory('js-user-scripts/final-segment')->set("chart_data",$segment->toJSON());
			$this->request->response = $view->render();
		}

		public function action_samplesegments(){
			$analysis = Helper_Service::factory("analysis",1);
			$selected_segments = $analysis->getSelectedSegments();
			
			$view = View::factory("components/sample-chart");
			$view->selected_segments = $selected_segments->getSelectedSegment(); 
						
			$this->request->response = $view->render();
			
			/*
			'id'   => array('data_type' => 'int',    'is_nullable' => FALSE),
    		'number' => array('data_type' => 'int',    'is_nullable' => TRUE), 
        	'segment'  => array('data_type' => 'string', 'is_nullable' => TRUE),
    		'analysis_id' => array('data_type'=>'int', 'is_nullable' => TRUE)
    		*/
			
		}
		
		public function action_samplepchart(){
						
						
			$segments_service = Helper_Service::factory("analysis",1)->getSelectedSegments();
			$segments = $segments_service->getSelectedSegment(); //devuelve un array de dao_selectedsegment
						
			$selected_segments = array();
			foreach ($segments as $current_seg){
				array_push($selected_segments, array("id"=>$current_seg->id, "number"=>$current_seg->number));
			}
						
			$sampleChart = View::factory("components/sample-chart");
			$sampleChart->selected_segments = $selected_segments;
			$sampleChart->data_url = "/diastole/test/getdata/";
			$sampleChart->thumb_url = "/diastole/test/getsegmenthumb/";
			
			$first_segment = $segments_service->getSegmentData($segments[0]->segment);
			$js_controller = View::factory("js-user-scripts/selected-segments")->set("chart_data",$first_segment->toJSON());
			
			$sampleChart->js_user_script = $js_controller->render();
			
			$this->request->response = $sampleChart->render();
		}
		
		public function action_getdata(){
			$id_segment = $this->request->param("id");	
			$segments_service = Helper_Service::factory("analysis",1)->getSelectedSegments();
			$selected = $segments_service->getSelectedSegment($id_segment);
			$segment_data = $segments_service->getSegmentData($selected->segment);
			$this->request->response = $segment_data->toJSON();
		}
		
		public function action_standalonepchart(){
			$this->request->response = View::factory("components/sample-chart")->render(); 
		}
		
		public function action_getsegmenthumb(){
			$id = $this->request->param("id");
			$segments_service = Helper_Service::factory("analysis",1)->getSelectedSegments();
			$selected = $segments_service->getSelectedSegment($id);
			$thumb = $segments_service->getSegmentData($selected->segment);
			$thumb->toChart("Segmento ".$selected->number,"Segment",true);
			//$segment = $analysis->getFinalSegment();
			//$segment->toChart("Registro Final","FinalSegment",true);
			
			
			/*$settings = Model::factory("chartsettings");
			$settings->seriesName = "FinalSegment";
			$settings->dataLabelSkip = 40;
			$settings->YAxisLabel = "Amplitud [%]";
			$settings->XAxisLabel = "Tiempo [ms]";
			$settings->setSeriesColor(55,91,127);
			$settings->setAxisBoundaries(0,100);
			$settings->chartHeight = 150;
			$settings->chartWidth = 150;
			$settings->chartTitle = "Segmento XXX";
			
			$chart = Model::factory("chart");			
			$chart->create($segment->getSamples(),$settings);
			
			$chart->stream();*/
		}
		
		/*Prueba de uso de conclusiones en el analysis*/
		public function action_reportconclusions(){
			$conclusions = Helper_Service::factory("conclusion")->getList();
			$report_conclusions = View::factory("analysis/content-report-template");
			$report_conclusions->templates = $conclusions;
			$report_conclusions->template_content_entity = "Conclusiones";
			$report_conclusions->templates_feed = "/diastole/test/getconclusionlist"; 
			$report_conclusions->preview_feed = "/diastole/test/getconclusion";
			$report_conclusions->template_new = "/diastole/test/newconclusion";
			$report_conclusions->content_save = "/diastole/test/savereportconclusion";
			
			$this->request->response = $report_conclusions->render();
		}
		
		public function action_getconclusionlist(){
			
			$filter = $_POST['filter'];
			
			//temporal
			if ($filter == "all"){
				//$templates_list = Helper_Service::factory("conclusion")->getList();
				$templates_list = ORM::factory("dao_conclusion")->find_all()->as_array();	
			}else if ($filter == "male"){
				$templates_list = ORM::factory("dao_conclusion")
													->where("male","=","1")
													->where("female","=","0")
													->find_all()->as_array();
			}else{
				$templates_list = ORM::factory("dao_conclusion")
													->where("female","=","1")
													->where("male","=","0")
													->find_all()->as_array();
			}
									
			$jsonTemplates = array();
			
			foreach($templates_list as $template){
				$jsonTemplates[]= "{'id':'".$template->id."','value':'".$template->conclusion_name."'}";
			}
						
			$this->request->response = "[".implode(",",$jsonTemplates)."]";
			
		}
		
		public function action_getconclusion(){
			$id = $_POST['id'];
			$conclusion = Helper_Service::factory("conclusion")->get($id);			
			$this->request->response = "{'template':'".$conclusion->conclusion."'}";
		}
		
		public function action_newconclusion(){
			$conclusion_form = View::factory("components/new-report-template");
			$conclusion_form->template_entity = "Conclusion";
			$conclusion_form->template_save_url = "/diastole/test/saveconclusion";  
			$this->request->response = $conclusion_form->render();
		}
		
		public function action_saveconclusion(){
			$data = array();
			$data['conclusion_name'] = $_POST['template_name']; 
			$data['conclusion'] = $_POST['template_description']; 
			
			if (($applicable = $_POST['applicable']) == "all"){
				$data['female'] = 1;
				$data['male'] = 1;	
			}elseif ($applicable == "male"){
				$data['female'] = 0;
				$data['male'] = 1;
			}else{
				$data['female'] = 1;
				$data['male'] = 0;
			}
						
			$this->request->response = Helper_Service::factory("conclusion")->save(0,$data);
		}
		
		public function action_savereportconclusion(){
			$this->request->response = $_POST["content"];
		}
		
		public function action_reportcomments(){
			
		}
		
		
		public function action_samplearguments(){
			$reply = "Ingresaste el parametro = ".$this->request->param("id").", seguido del numero = ".$this->request->param("id2");
			$this->request->response = $reply;
		}
		
		
		public function action_averagesbypathology(){
			$pathology = $this->request->param("id");
			
			$resultset = DB::query(Database::SELECT,"CALL diastole.average_by_pathology('".$pathology."');")->execute();
			
			echo var_dump($resultset);
			
			
		}
		
		
	}
?>